package so.shanku.essential.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.ShopThemeActivity;
import so.shanku.essential.adapter.ManBrandHotAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.Utils;
import striveen.util.used.view.view.XListView;

import java.util.*;

/**
 * Created by Administrator on 2015/9/7.
 */
public class ManBrandHotFragment extends BaseFragment {
	@ViewInject(R.id.xlistview_manbrand)
	private XListView xlistview_manbrand;
	@ViewInject(R.id.nodata_layout) //无数据
	private LinearLayout nodataLayout;
	private ManBrandHotAdapter manBrandHottAdapter;
	private boolean isFocus;
	private TextView tv_if_attentioned;
	private String id;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_manbrand, container, false);
		initCompont(view);
		xlistview_manbrand.setXListViewListener(xListLoadMore);
		xlistview_manbrand.setBoolInterceptTouchEvent(true);

		itemClick();
		Bundle bundle = getArguments();
		id = bundle.getString(Constant.ID);
		getData_BrandList(true);
		return view;
	}

	public void initCompont(View view) {
		ViewUtils.inject(this, view);
	}

	@Override
	public void onResume() {
		super.onResume();
		if(data_DownLoadlist!=null&&manBrandHottAdapter!=null){
			manBrandHottAdapter.setDatas(data_DownLoadlist);
			manBrandHottAdapter.notifyDataSetChanged();
		}
	}

	public void itemClick() {
		xlistview_manbrand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(position>0) {
					Bundle bundle = new Bundle();
					bundle.putString(Constant.VENDOR_ID, data_DownLoadlist.get(position - 1).getStringNoNull("VendorId"));
					bundle.putString(Constant.VENDOR_NAME, data_DownLoadlist.get(position - 1).getStringNoNull("ShopName"));
					activity.jumpTo(ShopThemeActivity.class, bundle, false);
				}
			}
		});
	}

	/**
	 * 获取品牌热门
	 */
	private final int what_GetBandHotList = 1;

	private void getData_BrandList(boolean chearAllData) {
		loadingToast.show();

		if (chearAllData) {
			data_DownLoadlist = null;
			if (manBrandHottAdapter != null) {
				manBrandHottAdapter.notifyDataSetChanged();
			}
			page = 0;
			xlistview_manbrand.setPullRefreshEnable(true);
			xlistview_manbrand.setPullLoadEnable(true);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);

		params.put("UserInfoId", Utils.getUserId(getActivity()));
		params.put("BrandTypeId", id);
		params.put("currentPage", page + 1);
		params.put("pageSize", pageSize);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_GetBandHotList);
		queue.setCallBack(callBack);
		queue.setParamsNoJson(params);
		queue.setWhat(what_GetBandHotList);
		getDataUtil.getData(queue);
	}


	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {

				if (ShowGetDataError.isOkAndCodeIsNot1(getActivity(),
						entity.getInfo())) {

					if (entity.getWhat() == what_GetBandHotList) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						setAdatper_singleSortlist(data);
						validateData();
					} else if (entity.getWhat() == GetDataConfing.WHAT_GET_FOCUS_ON) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						try {
							boolean isFocus = data.get(0).getBoolean("IsFocus", false);
							if (isFocus) {
								tv_if_attentioned.setSelected(true);
								tv_if_attentioned.setText(R.string.attentioned);

								MyApplication.getInstance().addAttendBrands(vendorId);
							} else {
								tv_if_attentioned.setSelected(false);
								tv_if_attentioned.setText(R.string.attention);
								MyApplication.getInstance().removeAttendBrands(vendorId);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

				}
			} else {
				ShowGetDataError.showNetError(getActivity());
			}
			loadingToast.dismiss();
			xlistview_manbrand.stopLoadMore();
			xlistview_manbrand.stopRefresh();
		}
	};

	private void validateData() {
		if (data_DownLoadlist == null || data_DownLoadlist.isEmpty()) {
			nodataLayout.setVisibility(View.VISIBLE);
			xlistview_manbrand.setVisibility(View.GONE);
		} else {
			nodataLayout.setVisibility(View.GONE);
			xlistview_manbrand.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 当前展示的数据
	 */
	private List<JsonMap<String, Object>> data_DownLoadlist;
	private int pageSize = 10;
	private int page = 0;

	private void setAdatper_singleSortlist(List<JsonMap<String, Object>> data) {

		if (data.size() == 0 || data.size() % pageSize != 0) {
			xlistview_manbrand.setPullLoadEnable(false);
//            if (page == 0 && data.size() > 0 || page != 0)
//                toast.showToast(R.string.xlistview_no_more_data);

		}
		if (page == 0) {
			this.data_DownLoadlist = data;
			manBrandHottAdapter = new ManBrandHotAdapter(getActivity(), data_DownLoadlist, callback2);
			xlistview_manbrand.setAdapter(manBrandHottAdapter);
			manBrandHottAdapter.notifyDataSetChanged();
            xlistview_manbrand.invalidateViews();
		} else {
			this.data_DownLoadlist.addAll(data);
			manBrandHottAdapter.notifyDataSetChanged();
		}
		page++;

	}

	XListView.IXListViewListener xListLoadMore = new XListView.IXListViewListener() {
		@Override
		public void onRefresh() {
			getData_BrandList(true);
		}

		@Override
		public void onLoadMore() {
			getData_BrandList(false);
		}
	};

	private String vendorId;
	private ManBrandHotAdapter.ItemAttentionChange callback2 = new ManBrandHotAdapter.ItemAttentionChange() {
		@Override
		public void onStatusChange(int position, TextView tv_if_attention) {
			tv_if_attentioned = tv_if_attention;
			vendorId = data_DownLoadlist.get(position).getStringNoNull("VendorId");
			if (Utils.isHasLogin(getActivity())) {
				activity.getDate_GetFocusOn(callBack, vendorId, getActivity());
			} else {
                activity.gotoLogin();
			}


		}
	};

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
        if(data_DownLoadlist!=null&&manBrandHottAdapter!=null){
            manBrandHottAdapter.setDatas(data_DownLoadlist);
            manBrandHottAdapter.notifyDataSetChanged();
        }
	}
}